package com.hotacorp.opencloud.common.resourcecommon.exception;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;

import com.hotacorp.opencloud.common.authcommon.SysUserBean;
import com.hotacorp.opencloud.common.commdata.Constants;

/**
 * 对从认证服务器返回的token信息进行解码，还原成包含userid,tenant_id(租户ID),dept_id,nick_name,user_phone信息的用户信息
 * @author lwg
 *
 */
public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {

	@Override
	public Map<String, ?> convertUserAuthentication(Authentication authentication) {
		Map<String, Object> response = new LinkedHashMap<>();
		response.put(USERNAME, authentication.getName());
		if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
			response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
		}
		return response;
	}

	@Override
	public Authentication extractAuthentication(Map<String, ?> map) {
		if (map.containsKey(USERNAME)) {
			Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
			
			Set<String> authoritiestrs = getAuthoritiestrs(map);
			String username = (String) map.get(Constants.USER_NAME);
			String nickname = (String) map.get(Constants.NICK_NAME);
			String phone = (String) map.get(Constants.USER_PHONE);
			Long userid = map.get(Constants.USER_ID)==null?null:Long.parseLong(map.get(Constants.USER_ID).toString());
			Long depid = map.get(Constants.DEPT_ID)==null?null:Long.parseLong(map.get(Constants.DEPT_ID).toString());
			Long tenantid = map.get(Constants.TENANT_ID)==null?null:Long.parseLong(map.get(Constants.TENANT_ID).toString());
			SysUserBean user = new SysUserBean(userid, username, "N/A", nickname, phone, tenantid, depid, true, authoritiestrs);
			return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
		}
		return null;
	}
	
	private Set<String> getAuthoritiestrs(Map<String, ?> map) {
		Object authorities = map.get(AUTHORITIES);
		if (authorities instanceof String) {
			return AuthorityUtils.authorityListToSet(AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities));
		}
		if (authorities instanceof Collection) {
			return AuthorityUtils.authorityListToSet(AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
					.collectionToCommaDelimitedString((Collection<?>) authorities)));
		}
		throw new IllegalArgumentException("Authorities must be either a String or a Collection");
	}

	private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
		Object authorities = map.get(AUTHORITIES);
		if (authorities instanceof String) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
		}
		if (authorities instanceof Collection) {
			return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
				.collectionToCommaDelimitedString((Collection<?>) authorities));
		}
		throw new IllegalArgumentException("Authorities must be either a String or a Collection");
	}
}